package com.psnoted.backend.controller;

import com.psnoted.backend.dto.*;
import com.psnoted.backend.service.AuthService;
import com.psnoted.backend.service.PasswordDataService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 密码数据控制器
 * 提供密码数据的获取和更新REST API接口
 *
 * @author PSNoted Team
 * @version 1.0.0
 */
@RestController
@RequestMapping("/passwords")
@Tag(name = "密码数据管理", description = "密码数据的获取和更新相关接口")
@CrossOrigin(origins = "*", maxAge = 3600)
public class PasswordDataController {

    private static final Logger logger = LoggerFactory.getLogger(PasswordDataController.class);

    @Autowired
    private PasswordDataService passwordDataService;

    @Autowired
    private AuthService authService;

    /**
     * 获取密码数据接口
     *
     * @param keyHash 用户密钥哈希
     * @param userKey 请求头中的用户密钥（用于身份验证）
     * @return 密码数据响应
     */
    @GetMapping
    @Operation(
        summary = "获取密码数据",
        description = "根据密钥哈希获取用户的加密密码数据"
    )
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "200",
            description = "获取成功",
            content = @Content(schema = @Schema(implementation = GetPasswordsResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "401",
            description = "用户未认证",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "404",
            description = "用户不存在",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "500",
            description = "服务器内部错误",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        )
    })
    public ResponseEntity<ApiResponse<GetPasswordsResponse>> getPasswords(
            @Parameter(description = "用户密钥哈希", required = true)
            @RequestParam String keyHash,
            @Parameter(description = "用户密钥（请求头，用于验证身份）", required = true)
            @RequestHeader("X-User-Key") String userKey) {

        logger.info("收到获取密码数据请求: keyHash={}, userKey={}", keyHash, userKey);

        try {
            // 验证用户身份
            if (!userKey.equals(keyHash)) {
                logger.warn("用户密钥不匹配: keyHash={}, userKey={}", keyHash, userKey);
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error(401, "用户身份验证失败"));
            }

            // 验证用户是否存在
            if (!authService.userExists(keyHash)) {
                logger.warn("用户不存在: keyHash={}", keyHash);
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error(404, "用户不存在"));
            }

            // 获取密码数据
            GetPasswordsResponse response = passwordDataService.getPasswordData(keyHash);

            String message = response.isHasData() ? "获取密码数据成功" : "用户暂无密码数据";
            logger.info("获取密码数据完成: keyHash={}, hasData={}", keyHash, response.isHasData());

            return ResponseEntity.ok(ApiResponse.success(message, response));

        } catch (Exception e) {
            logger.error("获取密码数据异常: keyHash={}, error={}", keyHash, e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(ApiResponse.error("获取密码数据失败: " + e.getMessage()));
        }
    }

    /**
     * 更新密码数据接口
     *
     * @param keyHash 用户密钥哈希
     * @param request 更新密码数据请求
     * @param userKey 请求头中的用户密钥（用于身份验证）
     * @return 更新结果响应
     */
    @PutMapping
    @Operation(
        summary = "更新密码数据",
        description = "更新指定用户的加密密码数据"
    )
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "200",
            description = "更新成功",
            content = @Content(schema = @Schema(implementation = UpdatePasswordsResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "400",
            description = "请求参数错误",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "401",
            description = "用户未认证",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "404",
            description = "用户不存在",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "409",
            description = "数据版本冲突",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "500",
            description = "服务器内部错误",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        )
    })
    public ResponseEntity<ApiResponse<UpdatePasswordsResponse>> updatePasswords(
            @Parameter(description = "用户密钥哈希", required = true)
            @RequestParam String keyHash,
            @Parameter(description = "更新密码数据请求", required = true)
            @Valid @RequestBody UpdatePasswordsRequest request,
            @Parameter(description = "用户密钥（请求头，用于验证身份）", required = true)
            @RequestHeader("X-User-Key") String userKey) {

        logger.info("收到更新密码数据请求: keyHash={}, userKey={}, timestamp={}",
            keyHash, userKey, request.getStorageData().getTimestamp());

        try {
            // 验证用户身份
            if (!userKey.equals(keyHash)) {
                logger.warn("用户密钥不匹配: keyHash={}, userKey={}", keyHash, userKey);
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error(401, "用户身份验证失败"));
            }

            // 验证用户是否存在
            if (!authService.userExists(keyHash)) {
                logger.warn("用户不存在: keyHash={}", keyHash);
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error(404, "用户不存在"));
            }

            // 验证请求数据中的keyHash与路径参数是否一致
            if (!keyHash.equals(request.getStorageData().getKeyHash())) {
                logger.warn("数据keyHash与路径参数不匹配: pathKeyHash={}, dataKeyHash={}",
                    keyHash, request.getStorageData().getKeyHash());
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ApiResponse.error(400, "数据密钥哈希不匹配"));
            }

            // 更新密码数据
            UpdatePasswordsResponse response = passwordDataService.updatePasswordData(keyHash, request.getStorageData());

            if (response.isSuccess()) {
                logger.info("更新密码数据成功: keyHash={}, timestamp={}",
                    keyHash, request.getStorageData().getTimestamp());
                return ResponseEntity.ok(ApiResponse.success("更新密码数据成功", response));
            } else {
                logger.warn("更新密码数据失败，存在冲突: keyHash={}", keyHash);
                return ResponseEntity.status(HttpStatus.CONFLICT)
                    .body(ApiResponse.error(409, "数据版本冲突，请先获取最新数据"));
            }

        } catch (Exception e) {
            logger.error("更新密码数据异常: keyHash={}, error={}", keyHash, e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(ApiResponse.error("更新密码数据失败: " + e.getMessage()));
        }
    }

    /**
     * 删除密码数据接口
     *
     * @param keyHash 用户密钥哈希
     * @param userKey 请求头中的用户密钥（用于身份验证）
     * @return 删除结果响应
     */
    @DeleteMapping
    @Operation(
        summary = "删除密码数据",
        description = "删除指定用户的所有密码数据"
    )
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "200",
            description = "删除成功",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "401",
            description = "用户未认证",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "404",
            description = "用户不存在",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "500",
            description = "服务器内部错误",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        )
    })
    public ResponseEntity<ApiResponse<String>> deletePasswords(
            @Parameter(description = "用户密钥哈希", required = true)
            @RequestParam String keyHash,
            @Parameter(description = "用户密钥（请求头，用于验证身份）", required = true)
            @RequestHeader("X-User-Key") String userKey) {

        logger.info("收到删除密码数据请求: keyHash={}, userKey={}", keyHash, userKey);

        try {
            // 验证用户身份
            if (!userKey.equals(keyHash)) {
                logger.warn("用户密钥不匹配: keyHash={}, userKey={}", keyHash, userKey);
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error(401, "用户身份验证失败"));
            }

            // 验证用户是否存在
            if (!authService.userExists(keyHash)) {
                logger.warn("用户不存在: keyHash={}", keyHash);
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error(404, "用户不存在"));
            }

            // 删除密码数据
            boolean deleted = passwordDataService.deletePasswordData(keyHash);

            if (deleted) {
                logger.info("删除密码数据成功: keyHash={}", keyHash);
                return ResponseEntity.ok(ApiResponse.success("删除密码数据成功", "OK"));
            } else {
                logger.warn("删除密码数据失败: keyHash={}", keyHash);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error(500, "删除密码数据失败"));
            }

        } catch (Exception e) {
            logger.error("删除密码数据异常: keyHash={}, error={}", keyHash, e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(ApiResponse.error("删除密码数据失败: " + e.getMessage()));
        }
    }

    /**
     * 获取密码数据统计信息
     *
     * @param keyHash 用户密钥哈希
     * @param userKey 请求头中的用户密钥（用于身份验证）
     * @return 统计信息响应
     */
    @GetMapping("/stats")
    @Operation(
        summary = "获取密码数据统计",
        description = "获取指定用户的密码数据统计信息"
    )
    @ApiResponses(value = {
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "200",
            description = "获取成功",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "401",
            description = "用户未认证",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        ),
        @io.swagger.v3.oas.annotations.responses.ApiResponse(
            responseCode = "404",
            description = "用户不存在",
            content = @Content(schema = @Schema(implementation = ApiResponse.class))
        )
    })
    public ResponseEntity<ApiResponse<Object>> getPasswordStats(
            @Parameter(description = "用户密钥哈希", required = true)
            @RequestParam String keyHash,
            @Parameter(description = "用户密钥（请求头，用于验证身份）", required = true)
            @RequestHeader("X-User-Key") String userKey) {

        logger.info("收到获取密码统计请求: keyHash={}, userKey={}", keyHash, userKey);

        try {
            // 验证用户身份
            if (!userKey.equals(keyHash)) {
                logger.warn("用户密钥不匹配: keyHash={}, userKey={}", keyHash, userKey);
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(ApiResponse.error(401, "用户身份验证失败"));
            }

            // 验证用户是否存在
            if (!authService.userExists(keyHash)) {
                logger.warn("用户不存在: keyHash={}", keyHash);
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(ApiResponse.error(404, "用户不存在"));
            }

            // 获取统计信息
            boolean hasData = passwordDataService.hasPasswordData(keyHash);
            long dataCount = passwordDataService.getPasswordDataCount(keyHash);

            Object stats = new Object() {
                public final boolean hasData = PasswordDataController.this.passwordDataService.hasPasswordData(keyHash);
                public final long dataCount = PasswordDataController.this.passwordDataService.getPasswordDataCount(keyHash);
            };

            logger.info("获取密码统计完成: keyHash={}, hasData={}, dataCount={}", keyHash, hasData, dataCount);
            return ResponseEntity.ok(ApiResponse.success("获取统计信息成功", stats));

        } catch (Exception e) {
            logger.error("获取密码统计异常: keyHash={}, error={}", keyHash, e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body(ApiResponse.error("获取统计信息失败: " + e.getMessage()));
        }
    }
}